package com.lqian.demo02.part2;

import com.lqian.demo02.utils.JDBCUtils;

import java.sql.*;

/**
 * 预编译，效率高。用问号占位，防止SQL注入
 * @author：Melody_LQ
 * @time：2022/7/13 4:24 下午
 */
public class TestPrepareStatement {

    public static void main(String[] args) {
        //login("jack","123456");
        //SQL注入
        login("'or '1=1","111111");
    }

    public static void login(String username,String password){
        Connection conn = null;
        PreparedStatement pre = null;
        ResultSet rs = null;

        try {
            conn = JDBCUtils.getConnection();
            String sql = "select * from users where name=? and password=?";
            pre= conn.prepareStatement(sql);
            System.out.println("====before==="+sql);
            pre.setString(1,username);
            pre.setString(2,password);
            System.out.println("====after==="+sql);
            rs = pre.executeQuery();
            System.out.println("sql---> "+sql);
            // select * from users where name='' or '1=1' and password = '111111'
           // select * from users where name'=''or ''1=1' and password='111111'
            while (rs.next()){
                System.out.println(rs.getString("name"));
                System.out.println(rs.getString("password"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.release(conn,pre,rs);
        }
    }

}
